package com.itheima.app.manager;

import cn.hutool.core.collection.CollUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.UserLocationService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.NearUserVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.RecommendUserVo;
import com.itheima.vo.VisitorVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class MakeFriendManager {

    @DubboReference
    RecommendUserService recommendUserService;

    @DubboReference
    UserInfoService userInfoService;

    @DubboReference
    VisitorService visitorService;

    @DubboReference
    UserLocationService userLocationService;

    @DubboReference
    QuestionService questionService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    public ResponseEntity findTodayBest() {
        //1.获取登陆者id
        //2.远程调用service查询今日最佳
        RecommendUser recommendUser = recommendUserService.findTodayBest(UserHolder.get().getId());

        //2.1今日最佳有可能不存在(新注册)
        if (recommendUser == null) {
            //若没有,设置一个默认的推荐用户
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1L);
            recommendUser.setScore(99D);
        }

        //3.通过最佳的用户id查询用户详情
        UserInfo userInfo = userInfoService.findById(recommendUser.getUserId());

        //4.封装vo对象且返回
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfo);
        vo.setFateValue(recommendUser.getScore().longValue());//缘分值

        return ResponseEntity.ok(vo);
    }


    // //推荐用户分页查询
    public ResponseEntity findRecommendUserByPage(Integer pageNum, Integer pageSize) {
        //1.获取登陆者id
        //2.远程调用service查询分页列表
        PageBeanVo pageBeanVo = recommendUserService.findByPage(UserHolder.get().getId(), pageNum, pageSize);

        //3.获取pageBeanVo中集合,遍历集合,获取每个推荐用户的id,然后获取userInfo,封装RecommendUserVo对象,将vo对象放入一个voList.
        //3.0 创建voList
        List<RecommendUserVo> voList = new ArrayList<>();

        //3.1 获取pageBeanVo中集合
        List<RecommendUser> items = (List<RecommendUser>) pageBeanVo.getItems();

        //3.2 遍历集合,获取每个推荐用户的id

        if (CollUtil.isNotEmpty(items)) {
            items.forEach(recommendUser -> {
                //3.3 获取userInfo
                UserInfo userInfo = userInfoService.findById(recommendUser.getUserId());

                //3.4 封装RecommendUserVo对象
                RecommendUserVo vo = new RecommendUserVo();
                vo.setUserInfo(userInfo);
                vo.setFateValue(recommendUser.getScore().longValue());

                //3.5 将vo对象放入voList中
                voList.add(vo);
            });
        }
        //4.给pageBeanVo设置voList,且返回
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }


    //查询推荐用户详情
    public ResponseEntity findPersonalInfo(Long jiaRenId) {
        //1.远程调用service查询推荐用户的userInfo
        UserInfo userInfo = userInfoService.findById(jiaRenId);

        //2.远程调用service查询俩用户的缘分值
        RecommendUser recommendUser = recommendUserService.findPersonalInfo(UserHolder.get().getId(), jiaRenId);

        //今日佳人可能不存在,因为当前用户是新用户设置的固定用户,所以推荐表中没有
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1L);
            recommendUser.setScore(90D);
        }

        //3.封装recommendUserVo且返回
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfo);
        vo.setFateValue(recommendUser.getScore().longValue());
        return ResponseEntity.ok(vo);
    }

    //交友访客,查询历史访客

    public ResponseEntity findVisitorsTop5() {
        //1.获取登陆者id
        Long userId = UserHolder.get().getId();

        //2.去redis中获取上次访问时间 (注意:新用户还没有最后访问时间)
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String timeStr = operations.get(ConstantUtil.LAST_ACCESS_TIME + userId);

        Long lastAccessTime;
        if (timeStr != null) {
            lastAccessTime = Long.parseLong(timeStr);
        } else {
            //设置默认时间或者项目上限时间
            lastAccessTime = new Date(0).getTime();
        }

        //3.远程调用service获取最近访客list
        List<Visitor> visitors = visitorService.findVisitorsTop5(userId, lastAccessTime);


        //4.遍历list,获取每个访客的userInfo,将userInfo封装成visitorVo,将每个vo放入voList中
        List<VisitorVo> voList = new ArrayList<>();
        if (CollUtil.isNotEmpty(visitors)) {
            visitors.forEach(visitor -> {
                UserInfo userInfo = userInfoService.findById(visitor.getVisitorUserId());

                VisitorVo vo = new VisitorVo();
                vo.setUserInfo(userInfo);
                vo.setFateValue(visitor.getScore().longValue());

                voList.add(vo);
            });
        }
        //5.将当前时间设置为最后访问时间(推荐失效)
        operations.set(ConstantUtil.LAST_ACCESS_TIME + userId, System.currentTimeMillis() + "", Duration.ofDays(7));

        //6.返回voList中
        return ResponseEntity.ok(voList);
    }

    // 调用manager
    public void saveUserLocation(Double longitude, Double latitude, String addrStr) {
        userLocationService.save(longitude, latitude, addrStr, UserHolder.get().getId());
    }


    //搜附近
    public ResponseEntity searchNear(String gender, Integer distance) {
        //1.远程调用service获取附近的人的id集合
        Long userId = UserHolder.get().getId();
        List<Long> ids = userLocationService.searchNear(userId, distance);

        //2.遍历id集合,获取每个用户的id,查询用户的UserInfo,将userInfo封装成NearUserVo对象,将每个vo放入声明好的voList中
        //2.1声明voList
        List<NearUserVo> voList = new ArrayList<>();

        //2.2遍历id集合,获取每个用户的id
        if (CollUtil.isNotEmpty(ids)) {
            for (Long id : ids) {
                //排除自己
                if (id.equals(userId)) {
                    continue;
                }

                //2.3查询用户的UserInfo
                UserInfo userInfo = userInfoService.findById(id);

                //筛选性别
                if (!gender.equals(userInfo.getGender())) {
                    continue;
                }

                //2.4将userInfo封装成NearUserVo对象
                NearUserVo vo = new NearUserVo();
                vo.setUserId(id);
                vo.setNickname(userInfo.getNickname());
                vo.setAvatar(userInfo.getAvatar());

                //2.5将每个vo放入声明好的voList中
                voList.add(vo);
            }
        }

        //3.返回voList
        return ResponseEntity.ok(voList);
    }

    // 查看对方的陌生人问题
    public ResponseEntity findStrangerQuestions(Long userId) {
        //1.远程调用questionService查询用户的问题
        Question question = questionService.findByUserId(userId);

        //2.若返回的对象不存在,设置默认问题且返回
        if (question==null) {
            question=new Question();
        }
        return ResponseEntity.ok(question.getStrangerQuestion());
    }
}
